import 'dart:ui';

import 'package:flame/components/component.dart';
import 'package:hello_flutter/demo/game/game_controller.dart';

class EnemySpawner extends Component {
  EnemySpawner(this.controller) {
    initialize();
  }

  final GameController controller;
  final int maxSpawnInternel = 3000; // 最大敌人出现时间
  final int minSpawnInternel = 700; // 最小敌人出现时间
  final int intervalChange = 3; // 改变间隔
  final int maxEnemies = 7; // 最多敌人数量
  int currentInterval = 0; // 当前间隔
  int nextSpawn; // 下个敌人出现时间

  void initialize() {
    killAllEnemies();
    currentInterval = maxSpawnInternel;
    nextSpawn = DateTime.now().millisecondsSinceEpoch + currentInterval;
  }

  void killAllEnemies() {
    controller.enemies.forEach((enemy) => enemy.isDead = true);
  }

  @override
  void render(Canvas c) {}

  @override
  void update(double t) {
    final now = DateTime.now().millisecondsSinceEpoch;
    // 敌人数量未超出最大限制, 且当前时间戳高于下一次产生时间
    if (controller.enemies.length < maxEnemies && now >= nextSpawn) {
      controller.spawnEnemy();
      if (currentInterval > minSpawnInternel) {
        currentInterval -= intervalChange;
        currentInterval -= (currentInterval * 0.1).toInt();
      }
      nextSpawn = now + currentInterval;
    }
  }
}
